<template>
  <div>
    <a-card class="card"> 设施农业用地备案表 </a-card>
    <div
      style="padding: 0 15px"
      v-if="xmjd == 2 || role == 'shi' || role == 'sheng'"
    >
      <div class="wjsc">外业核查照片</div>
      <div class="xz">
        <a-button type="primary" size="small" @click="PlXdown"
          >批量下载</a-button
        >
      </div>
      <a-table
        bordered
        ref="table"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
      >
        <span slot="filename" slot-scope="text, record">
          <a @click="YlwJ(record)">{{ text }}</a>
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="DownWj(record)" v-if="record.filepath != null">下载</a>
        </span>
      </a-table>
    </div>
    <div style="padding: 0 15px" v-else>
      <div class="wjsc">外业核查照片</div>
      <div></div>
      <div>
        <a-upload-dragger
          :file-list="fileList"
          :multiple="true"
          :remove="handleRemove"
          :before-upload="handleBeforeUpload"
          accept="image/*,"
          :openFileDialogOnClick="false"
          @change="handleFileChange"
          :showUploadList="false"
        >
          <div style="min-height: 200px">
            <div class="ft" v-if="fileList.length == 0">
              拖拽文件在这里.....
            </div>
            <div class="box-content">
              <div v-for="(item, index) in fileList" :key="index" class="box">
                <img
                  :src="item.base64Image"
                  alt=""
                  style="
                    min-width: 100px;
                    max-width: 400px;
                    height: auto;
                    background-size: 100%;
                    max-height: 160px;
                  "
                />
                <div class="box-footer">
                  <div style="line-height: 13px">{{ item.filename }}</div>
                  <div>
                    <a-icon
                      type="plus-circle"
                      v-if="!item.id"
                      theme="twoTone"
                      @click="addok(item, index)"
                      style="font-size: 18px"
                    />&nbsp;&nbsp;<a-icon
                      type="delete"
                      style="color: red; font-size: 18px"
                      @click="deleteodd(item, index)"
                    />
                  </div>
                </div>
                <div><a-progress :percent="percent" v-if="!item.id && isprogress == true" /></div>
              </div>
            </div>
          </div>
        </a-upload-dragger>
      </div>
      <div><a-progress :percent="percent" v-if="isprogress == true" /></div>
      <br />
      <a-button type="primary" @click="deAll" v-if="isimg == false"
        >删除</a-button
      >
      <span v-if="isimg == false > 0">&nbsp;&nbsp;</span>
      <a-button type="primary" @click="saveimg" v-if="isimg == false"
        >上传</a-button
      >
      <span v-if="isimg == false > 0">&nbsp;&nbsp;</span>
      <a-upload
        :file-list="fileList"
        :remove="handleRemove"
        :before-upload="handleBeforeUpload"
        accept="image/*,"
        @change="handleFileChange"
        :showUploadList="false"
      >
        <a-button> <a-icon type="upload" /> 选择文件 </a-button>
        <br />
      </a-upload>
    </div>
  </div>
</template>
  
  <script>
import axios from "axios";
import { Uploadfile } from "../../../api/api2.js";
import {
  zfilesList,
  download,
  zfilespreview,
  Alldown,
  showImage,
  deleteImage,
} from "../../../api/api";
export default {
  props: {
    xmjd: {
      type: String,
      require: true,
    },
  },
  data() {
    return {
      role: JSON.parse(localStorage.getItem("user")).role,
      columns: [
        {
          title: "IDX",
          dataIndex: "",
          key: "rowIndex",
          width: 50,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          title: "类别",
          dataIndex: "type",
          align: "center",
          // scopedSlots: { customRender: "type" },
          customRender: (value, row, index) => {
            console.log(row, index, "index");
            let arr = this.dataSource.filter((item) => item.filekind == 0);
            let btt = this.dataSource.filter((item) => item.filekind == -1);
            let indexA1 = this.dataSource.findIndex(
              (item) => item.filekind == 0
            );
            let indexA0 = this.dataSource.findIndex(
              (item) => item.filekind == -1
            );

            if (this.dataSource.length == 2) {
              return value;
            } else {
              if (index == indexA1) {
                var obj = {
                  children: "核查照片",
                  attrs: { rowSpan: arr.length },
                };
                return obj;
              } else if (index == indexA0) {
                var obj = {
                  children: "其他",
                  attrs: { rowSpan: btt.length },
                };
                return obj;
              } else {
                var obj = {
                  children: "",
                  attrs: { rowSpan: 0 },
                };
                return obj;
              }
            }
          },
        },
        {
          title: "文件名",
          dataIndex: "filename",
          align: "center",
          scopedSlots: { customRender: "filename" },
        },
        {
          title: "上传时间",
          dataIndex: "adddate",
          align: "center",
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action" },
        },
        ,
      ],
      dataSource: [],
      filename: "",
      filepath: "",
      id: "",
      filesize: "",
      ispatn: "",
      fileList: [],
      imgdata: [],
      isimg: false,
      percent: 0,
      isprogress:false
    };
  },
  async mounted() {
    console.log(this.xmjd, "////");
    //获取文件列表
    this.getdata();
  },
  methods: {
    async getdata() {
      const params = {
        jbxxsec: this.$route.query.id,
      };
      const res = await showImage(params);
      if (res.code == 200) {
        if (res.result.length > 0) {
          this.isimg = true;
        }
      }
      this.fileList = res.result;
      if (this.xmjd == 2 || this.role == "shi" || this.role == "sheng") {
        // this.imgdata = res.result;
        res.result.push(
          {
            type: "核查照片",
            add: "",
            filekind: 0,
          },
          {
            type: "其他",
            add: "",
            filekind: -1,
          }
        );
        let arr = res.result.filter((item) => item.filekind == 0);
        let btt = res.result.filter((item) => item.filekind == -1);
        if (arr.length > 1 || btt.length > 1) {
          const a = arr.filter((item) => item.hasOwnProperty("filename"));
          const b = btt.filter((item) => item.hasOwnProperty("filename"));
          const cdd = btt.length > 1 ? arr.concat(b) : a.concat(btt);
          cdd.map((item) => {
            item["add"] = "";
            item["action"] = "";
            item["type"] = item.filekind == 0 ? "核查照片" : "其他";
            return item;
          });
          console.log(cdd, arr, "cdd");

          this.dataSource =
            arr.length == 0
              ? cdd.filter((item) => item.hasOwnProperty("filename"))
              : cdd.length >= 3 && btt.length >= 2
              ? cdd.filter((item) => item.hasOwnProperty("filename"))
              : cdd;
        } else {
          let ctt = arr.concat(btt);
          ctt.map((item) => {
            item["add"] = "";
            item["action"] = "";
            return item;
          });
          this.dataSource = ctt;
        }
      }
    },
    exportselect(text, record, index) {
      console.log(text, record, index, "1111");
      this.ispatn = record.filekind;
      // 创建一个隐藏的input元素
      const input = document.createElement("input");
      input.type = "file";
      input.accept = "application/pdf";
      input.style.display = "none";

      // 监听input元素的change事件
      input.addEventListener("change", (event) => {
        const file = event.target.files[0];
        console.log(file, "files");
        this.dataSource[index].add = file.name;
        // 在这里可以对文件进行处理，比如上传到服务器或进行其他操作
        this.uploadFile(file);
      });

      // 触发input元素的点击事件
      input.click();
    },
    async uploadFile(file) {
      let formData = new FormData();
      formData.append("file", file);
      formData.append("jbxxSec", this.$route.query.id);
      axios
        .post(
          process.env.VUE_APP_API_BASE_URL + `/fileupdates/zfiles/uploadPDF`,
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data",
              "Jmt-Token": localStorage.getItem("token"),
            },
          }
        )
        .then((res) => {
          console.log(res, "res");
          const data = res.data.result;
          this.filename = data.name;
          this.filepath = data.path;
          this.filesize = data.size;
        });
    },
    //下载文件
    async DownWj(data) {
      var name = data.filename;
      const res = await download({ fileName: data.filepath });
      // 将富文本内容转换为Blob对象
      const blob = new Blob([res], { type: "text/html" });
      const url = window.URL.createObjectURL(blob);
      // 创建一个a标签，设置href属性为URL对象的URL，设置download属性为要保存的文件名
      const a = document.createElement("a");
      a.href = url;
      a.download = `${name}.png`;
      a.style.display = "none";
      document.body.appendChild(a);
      // 模拟点击a标签来下载文件
      a.click();
      // 释放URL对象
      window.URL.revokeObjectURL(url);
    },
    async YlwJ(data) {
      const res = await zfilespreview({ fileName: data.filepath });
      const blob = new Blob([res], { type: "image/jpeg" });
      // 创建一个指向Blob的URL
      const url = window.URL.createObjectURL(blob);
      // 在新标签页中打开PDF
      window.open(url);
    },
    //批量下载
    async PlXdown() {
      const res = await Alldown({ id: this.$route.query.id, type: "1" });
      // 将富文本内容转换为Blob对象
      const blob = new Blob([res], { type: "'application/zip,charset=utf-8'" });
      const url = window.URL.createObjectURL(blob);
      // 创建一个a标签，设置href属性为URL对象的URL，设置download属性为要保存的文件名
      const a = document.createElement("a");
      a.href = url;
      a.download = `files.zip`;
      a.style.display = "none";
      document.body.appendChild(a);
      // 模拟点击a标签来下载文件
      a.click();
      // 释放URL对象
      window.URL.revokeObjectURL(url);
    },
    handleBeforeUpload(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        console.log("图片预览", e.target.result);
        this.fileList = [
          ...this.fileList,
          {
            uid: file.uid,
            filename: file.name,
            status: "done",
            base64Image: e.target.result,
            originFileObj: file,
          },
        ];
      };
      reader.readAsDataURL(file);

      return true;
    },
    handleFileChange({ fileList }) {
      // console.log(fileList,'fileList111');
      this.isimg = false;
      // const list = fileList;
      // this.fileList = fileList;
      // console.log(list, "////");
      // const arr = list.map((item) => {
      //   item["filename"] = item.name;
      //   item['url'] = item.url
      //   return item;
      // });
      // const data = arr.concat(this.imgdata);
      // this.imgdata = Array.from(new Set(data));
      // this.imgdata = fileList;
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    //删除
    deAll() {
      this.fileList = [];
      this.getdata();
    },
    //上传
    async saveimg() {
      if (this.fileList.length > 0) {
        this.isprogress = true
        this.percent = 100;
        var data = new FormData();
        this.fileList.forEach((file) => {
          data.append("imageFiles", file.originFileObj);
        });
        data.append("fkflow", "003");
        data.append("jbxxsec", this.$route.query.id);
        data.append("kindvalue", "0");
        const result = await Uploadfile(data);
        if (result.data.code == 200) {
          this.$message.success("上传成功");

          setTimeout(() => {
            this.imgdata = [];
            this.fileList = [];
            this.percent = 0;
            this.getdata();
            this.isprogress = false
          }, 1500);
        } else {
          this.$message.error(res.data.message);
        }
      } else {
        this.$message.warn("请选择图片上传！");
      }
    },
    //单个删除
    async deleteodd(data, index) {
      console.log(data.id, "111");
      if (data.id != null) {
        const params = {
          datedesc: data.jbxxSec,
          filekind: data.filekind,
          fkflow: data.fkFlow,
          id: data.id,
        };
        const res = await deleteImage(params);
        if (res.code == 200) {
          this.$message.success("删除成功");
          this.getdata();
        } else {
          this.$message.error(res.data.message);
        }
      } else {
        console.log(this.fileList, "111");
        // this.imgdata.splice(index, 1);
        this.fileList.splice(index, 1);
        this.$message.success("删除成功");
        // this.getdata()
      }
    },
    //单个添加
    async addok(res) {
      var data = new FormData();
      data.append("imageFiles", res.originFileObj);
      data.append("fkflow", "003");
      data.append("jbxxsec", this.$route.query.id);
      data.append("kindvalue", "0");
      const result = await Uploadfile(data);
      if (result.data.code == 200) {
        this.$message.success("上传成功");
        this.fileList = [];
        this.getdata();
      } else {
        this.$message.error(res.data.message);
      }
    },
  },
};
</script>
  
  <style lang="less" scoped>
.card {
  font-weight: 700;
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue",
    "PingFang SC", "Microsoft YaHei", "Source Han Sans SC", "Noto Sans CJK SC",
    "WenQuanYi Micro Hei", sans-serif;
  color: #313944;
  letter-spacing: 0.5px;
  text-align: center;
  height: 50px;
  line-height: 0px;
  font-size: 18px;
}
.wjsc {
  margin-top: 10px;
  padding-top: 6px;
  padding-bottom: 6px;
  display: table;
  width: 100%;
  padding-left: 25px;
  border-bottom: 1px solid rgba(77, 82, 89, 0.05);
  background-color: #48b0f7 !important;
  color: #fff !important;
}
.xz {
  border: 1px solid #f0f0f0;
  padding: 10px;
}
.btn {
  margin-left: 60px;
}
.ft {
  color: #aaa;
  font-size: 40px;
  line-height: 200px;
}
.box-content {
  display: flex;
  flex-wrap: wrap;
  min-width: 200px;
  // height: 300px;
}
.box-footer {
  display: flex;
  padding: 10px;
  justify-content: space-between;
}
.box {
  // display: flex;
  // flex-wrap: wrap;
  // flex-direction: column;
  min-width: 200px;
  // min-height: 160px;
  border: 1px solid #ddd;
  box-shadow: 1px 1px 5px 0 #a2958a;
  margin-left: 8px;
}
</style>